package com.candy.candysocket.netty;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.net.InetAddress;

/**
 * @author suYanLong
 * @version 1.0
 * @date 2023/8/17 14:52
 * @Description 将netty服务注册到nacos中
 */
@Component
public class NettyRegistryNacos {

    @Value("${netty.port:8890}")
    private Integer port;

    @Value("${netty.application.name:netty-server}")
    private String serverName;

    @Resource
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @PostConstruct
    public void start() throws Exception {
        //注册到 Nacos 中
        registerNamingService(serverName, String.valueOf(port));
    }

    /**
     * 注册到 nacos 服务中
     * 手动注册
     *
     * @param nettyName netty服务名称
     * @param nettyPort netty服务端口
     */
    private void registerNamingService(String nettyName, String nettyPort) {
        try {
            NamingService namingService = NamingFactory.createNamingService(nacosDiscoveryProperties.getServerAddr());
            InetAddress address = InetAddress.getLocalHost();
            namingService.registerInstance(nettyName, address.getHostAddress(), Integer.parseInt(nettyPort));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
